/**
 * 书籍控制器模块
 * controller\book.js
 *
 * 说明：
 * 中间件处理路由请求：
 * 1. req.params --> 路由参数 /:id  -> req.params.id
 * 2. req.query  --> url查询串  ?k1=v1&k2=v2  -> req.query.k1, req.query.k2
 * 3. req.body   --> 数据对象  {k1:v1, k2:v2} -> req.body.k1, req.body.k2
 *
 * 中间件进行异步封装（async/await），不会直接执行，需要进行函数立即执行的方式。
 */
 
const express = require("express");
 
const util = require("../common/util");

//访问book数据模型
/**
 * @typedef {BookDB}
 */
const BookDB = require("../model/sqlite/book");

/**
 * 获取书籍信息
 * @param {express.Request} req 请求
 * @param {express.Response} res 响应
 */
function find(req,res){
    // 异步函数会自动返回一个 Promise 对象.自动调用函数
    (async function(){
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.find(req.params.id);
        // await db.close()
        // %O输出一个对象
        util.logFormat(`获取【${req.params.id}】书籍信息${Date.now()}%O`,result);
        res.json(util.FormatJSONData(200,`获取书籍信息【${req.params.id}】`,result));
    })();
}

/**
 * 获取书籍信息列表
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function findAll(req,res){
    (async function(){
        //1.处理输入的数据
        //FIXME: 输入数据的正确性校验，一致性校验，完整性校验
        let limit = req.query.limit ? req.query.limit : -1;
        let offset = req.query.offset ? req.query.offset : -1;
        //2. 访问数据
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.findAll(limit, offset);
        //await db.close();

        //输出数据
        // %O输出一个对象
        util.logFormat(`获取【limit=${limit}&offset=${offset}】书籍信息%O`,result);
        res.json(util.FormatJSONData(200,`获取书籍信息列表`,result));
    })();
}
/**
 * 新增书籍信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function add(req,res){
    (async function(){
        let book = {
            //FIXME:req.body的数据安全性校验
            title: req.body.title,
            pic: req.body.pic,
            localPic: req.body.localPic, //FIXME:处理远程图片为本地图片
            author: req.body.author,
            publisher: req.body.publisher,
            producer: req.body.producer,
            subtitle: req.body.subtitle,
            originalTitle: req.body.originalTitle,
            translator: req.body.translator,
            pubdate: req.body.pubdate,
            pages: req.body.pages,
            price: req.body.price,
            binding: req.body.binding,
            series: req.body.series,
            isbn: req.body.isbn,
            intro: req.body.intro,
            doubanId: req.body.doubanId,
            created_time: Date.now(),
            updated_time: Date.now(),
        };
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.add(book);

        //await db.close();

        //输出数据
        util.logFormat(`新增书籍信息：lastId->${result}`);
        res.json(util.FormatJSONData(201,`新增书籍信息`, { lastID: result }));
    })();
}
/**
 * 更新书籍信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function update(req,res){
    (async function(){
        let book = {
            //FIXME:req.body的数据安全性校验
            id:req.params.id,
            title: req.body.title,
            pic: req.body.pic,
            localPic: req.body.localPic, //FIXME:处理远程图片为本地图片
            author: req.body.author,
            publisher: req.body.publisher,
            producer: req.body.producer,
            subtitle: req.body.subtitle,
            originalTitle: req.body.originalTitle,
            translator: req.body.translator,
            pubdate: req.body.pubdate,
            pages: req.body.pages,
            price: req.body.price,
            binding: req.body.binding,
            series: req.body.series,
            isbn: req.body.isbn,
            intro: req.body.intro,
            doubanId: req.body.doubanId,
            updatedTime: Date.now(),
        };
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.update(book);

        //await db.close();

        //输出数据
        util.logFormat(`修改书籍信息：lastId->${result}`);
        res.json(util.FormatJSONData(201,`修改书籍信息`, { change: result }));
    })();
}
/**
 * 删除书籍信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function remove(req,res){
    (async function(){
        //FIXME:req.body的数据安全性校验
        let bookId = req.params.id;
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.remove(bookId)

        util.logFormat(`删除【${bookId}】书籍信息%O`,result);
        res.json(util.FormatJSONData(200,`删除书籍信息【${bookId}】`,result));
    })();
}

/**
 * 获取书籍总数
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function getCount(req,res){
    (async function(){
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.getCount()

        util.logFormat(`获取书籍总数：${result}`);
        res.json(util.FormatJSONData(200,`获取书籍总数`,result));
    })();
}

/**
 * 查找书籍
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function search(req,res){
    (async function(){
        //1.处理输入的数据
        //FIXME: 输入数据的正确性校验，一致性校验，完整性校验
        let q = req.query.q;
        let limit = req.query.limit ? req.query.limit : -1;
        let offset = req.query.offset ? req.query.offset : -1;
        //2. 访问数据
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.search(q,limit, offset);
        //await db.close();

        //输出数据
        // %O输出一个对象
        util.logFormat(`获取关键字为【q=${q}】【limit=${limit}&offset=${offset}】书籍信息%O`,result);
        res.json(util.FormatJSONData(200,`获取指定关键字书籍信息列表`,result));
    })();
}

/**
 * 通过isbn查找书籍
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function findByIsbn(req,res){
    (async function(){
        //1.处理输入的数据
        //FIXME: 输入数据的正确性校验，一致性校验，完整性校验
        //2. 访问数据
        let db = BookDB.getInstance();
        await db.connect();
        let result = await db.findByIsbn(req.params.isbn);
        //await db.close();

        //输出数据
        // %O输出一个对象
        util.logFormat(`获取关键字为【${req.params.isbn}】书籍信息%O`,result);
        res.json(util.FormatJSONData(200,`获取指定ISBN的书籍信息`,result));
    })();
}

module.exports = {
    find,
    findAll,
    add,
    update,
    remove,
    getCount,
    search,
    findByIsbn
}